<!--
 * @Description: 项目库列表页面
 * @Author: hujingshan hujs@tysoft.com
 * @Date: 2024-04-23 15:07:36
 * @FilePath: index.vue
-->
<template>
  <div class="project-content" v-if="searchTypeList.length">
    <ty-plm-operate-table ref="table" :load="load" @refresh="refresh" view-type="ProjectRequestView"
      :operates="operates" :transformColumns="transformColumns" :typeList="searchTypeList" :has-checked-box="false"
      :defaultCondition="defaultCondition" :sortColumns="sortColumns">
      <template #operate>
        <ty-plm-radio v-model="operation" v-bind="projectOptions" @change="refresh"></ty-plm-radio>
        <ty-plm-button style="margin-left: 8px" v-if="!isMy" :options="{
          title: $t('btn.create'),
          type: 'main',
          iconClass: 'iconfont icon-a-operation-newlybuild'
        }" @click="create"></ty-plm-button>
          <ty-plm-button @click="triggerFileInput" v-show="isPMO">批量导入年度计划</ty-plm-button>
        <el-button type="button" style="text-align: center;background-color: #055DD5;color: white; "
          @click="modelLoadingFunc" :loading="modelLoading"  v-show="isPMO">
          模板下载
        </el-button>
        <input ref="fileInputRef" type="file" accept=".xlsx" style="display: none" @change="handleFileChange" />
      </template>

      <template #column-starred="{ row }">
        <ty-plm-button :options="{
          type: 'text',
          iconClass: `${row.starred ? 'iconfont icon-shiwujiaoxing starred' : 'iconfont icon-kongwujiaoxing'}`,
          content: `${row.starred ? $t('btn.cancelStar') : $t('btn.star')}`
        }" @click="handleStar(row)"></ty-plm-button>
      </template>
      <template #column-name="{ row }">
        <span :class="{ 'project-name': isCheckViewPermission ? calcResult2('查看', [row]) : true }"
          @click="goToProjectDetail(row)">
          {{ row.name }}
        </span>
      </template>
      <template #column-completionStatus="{ row }">

        <div class="tag" :style="statusOptions[row.completionStatus]?.style || {}">
          {{ statusOptions[row.completionStatus]?.label || '' }}
          <!-- statusOptions[row.completionStatus]?.label -->
        </div>
      </template>
      <template #column-creatorDisplayName="{ row }">
        <ty-plm-user :row="row" :userObj="{ account: row.creatorName, subValue: row.creatorName }"
          :value="row.creatorFullName"></ty-plm-user>
      </template>
      <template #column-updatorDisplayName="{ row }">
        <ty-plm-user :row="row" :userObj="{ account: row.updatorName, subValue: row.updatorName }"
          :value="row.updatorFullName"></ty-plm-user>
      </template>
      <template #column-percentWorkComplete="{ row }">
        <div class="progress-content">
          <div class="progress">
            <div class="process-inner"
              :style="{ width: `${Number(parseFloat((row.percentWorkComplete || 0) * 100).toFixed(2))}%` }"></div>
          </div>
          <div class="progress-number">{{ Number(parseFloat((row.percentWorkComplete || 0) * 100).toFixed(2)) }}%</div>
        </div>
      </template>
      <template #column-projectManager="{ row }">
        <ty-plm-tag-dropDown v-model="cloneDeep(row).projectManagerList"
          :options="{ tagCount: 1, labelKey: 'value', disabled: true }" :viewType="'info'"></ty-plm-tag-dropDown>
      </template>
      <template #column-finishDateDeff="{ row }">
        <span v-if="row.finishDateDeff">
          <span>{{ row.finishDateDeff < 0 ? $t('label.overdue') : $t('label.surplus') }}</span>
              <span class="day" :class="{ overdue: row.finishDateDeff < 0 }">
                {{ Math.abs(row.finishDateDeff) > 999 ? '999+' : Math.abs(row.finishDateDeff) }}
              </span>
              <span>{{ $t('label.day') }}</span>
          </span>
      </template>
      <!-- 新增：当前阶段完成时间列插槽 -->
      <template #column-currentStageFinishDate="{ row }">
        <span>
          {{ row.finish ? row.finish : '-' }}
        </span>
      </template>

      <template #column-curMileStoneName="{ row }">
        <span>
          {{ row.projectCompleted === true ? '已完成' : (row.curMileStoneName || '-') }}
        </span>
      </template>
    </ty-plm-operate-table>

    <ty-plm-dialog v-model="showProject" :options="projectCreateOptions" @doConfirm="doConfirm">
      <!-- <project-create ref="projectCreateRef"></project-create> -->
      <component :is="projectTest" ref="projectCreateRef"></component>
    </ty-plm-dialog>

    <!-- 弹窗子组件 -->
  </div>
</template>
<script setup>
import { cloneDeep } from 'lodash';
const ProjectCreate = tyRoot.getExportResource('src/modules/rpm/business-module/project/components/project-create.vue').default;
import projectTest from './components/project-create.vue';
import { useProjectLib, createProps, useOverride } from './index.js';
import core from '@common/core'
import axios from 'axios';
import { ref, onBeforeMount, inject, getCurrentInstance, watch, nextTick } from 'vue';
  const { proxy } = getCurrentInstance();
const request = core.getExportResource('src/core/utils/http-tools.js').default;
// const props = defineProps(createCompProps());
const props = defineProps(createProps());
const {
  isPMO,
  operates,
  searchTypeList,
  table,
  projectCreateRef,
  operation,
  projectCreateOptions,
  showProject,
  statusOptions,
  projectOptions,
  load,
  goToProjectDetail,
  transformColumns,
  handleStar,
  refresh,
  doConfirm,
  create,
  sortColumns,
  isCheckViewPermission,
  calcResult2,
  defaultCondition,
  batchImporTnnualPlan,
  showModalUploadModal
} = (useOverride || useProjectLib)(props);

const fileInputRef = ref(null);


// 触发文件选择框
const triggerFileInput = () => {
  fileInputRef.value.click();
};
const modelLoadingFunc = async (event) => {
  const button = event.currentTarget;
  button.disabled = true;
  button.textContent = "下载中...";
  try {
    let fileName = '年度计划导入模板.xlsx';
    const response = await axios.get(
      '/rest/v1/history/downloadTemplate',
      {
        params: {
          fileName
        },
        headers: {
          authorization: sessionStorage.getItem('authorization') || '',
          'X-Requested-With': 'XMLHttpRequest'
        },
        responseType: 'blob', // 强制响应为二进制流（核心！）
        timeout: 10000
      }
    );
    const contentDisposition = response.headers['content-disposition'];
    if (contentDisposition) {
      // 兼容后端可能的文件名格式（如 filename="xxx.xlsx" 或 filename=xxx.xlsx）
      const match = contentDisposition.match(/filename(?:\*=UTF-8''|=)["']?([^'";\n]+)["']?/i);
      if (match && match[1]) {
        fileName = decodeURIComponent(match[1]); // 解码中文/特殊字符
      }
    }


    const blob = new Blob([response.data], {
      // 明确Excel文件的MIME类型（避免浏览器识别错误）
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });
    const downloadUrl = window.URL.createObjectURL(blob);

    // 创建隐藏的<a>标签，模拟点击后移除（不影响页面）
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = downloadUrl;
    a.download = fileName; // 控制下载的文件名
    document.body.appendChild(a);
    a.click(); // 触发下载

    // 5. 清理临时资源（避免内存泄漏）
    document.body.removeChild(a);
    window.URL.revokeObjectURL(downloadUrl);

  } catch (error) {
    // 6. 错误处理（不跳转，只提示）
    console.error('下载失败:', error);
    alert('下载失败：' + (
      error.response?.data
        ? await error.response.data.text() // 若后端返回错误文本，显示具体原因
        : '网络超时或接口异常'
    ));
  } finally {
    // 7. 无论成功/失败，恢复按钮状态
    button.textContent = "模板下载";
    button.disabled = false;
  }
}
// 处理文件选择变化
const handleFileChange = async (event) => {
  const file = event.target.files[0];
  if (!file) return;

  // 保存 target 引用，避免异步后 event 被回收
  const fileInput = event.target;

  // 校验文件类型
  const isValidType = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.name.endsWith('.xlsx');
  if (!isValidType) {
    proxy.$message.error('只能上传 .xlsx 格式的文件');
    fileInput.value = ''; // 清空无效文件
    return;
  }

  // 构造 FormData
  const formData = new FormData();
  formData.append('file', file);

  try {
    const res = await request({
      method: 'post',
      url: '/typrjmng/api/v1/project/import',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    if (res.data.success) {
      proxy.$message.success('上传成功');
    } else {
      proxy.$message.error('上传失败: ' + res.data.message);
    }
  } catch (error) {
    console.error('上传错误:', error);
    proxy.$message.error('上传失败，请重试');
  } finally {
    // ✅ 在 finally 中清空 input，确保总会执行
    fileInput.value = '';
  }
};
</script>
